package com.ki.rent.controller;

import com.google.gson.Gson;
import com.ki.rent.entity.House;
import com.ki.rent.entity.User;
import com.ki.rent.service.HouseService;
import com.ki.rent.service.UploadService;
import com.ki.rent.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import io.swagger.annotations.ApiOperation;


@Controller
public class AddHouseController {



	@Autowired
	private HouseService houseService;
	@Autowired
	private UserService userService;
	@Autowired
	private UploadService mUploadService;

	@RequestMapping("/MultipleUpload")
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("file") List<MultipartFile> file, HttpServletRequest req) throws IOException {
		return mUploadService.uploadFile(file.get(0));
	}

	@RequestMapping("/singleUpload")
	@ResponseBody
	public Map<String, Object> singleUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req,
											HttpSession session) throws IOException {
		return mUploadService.uploadFile(file);
	}

	@ResponseBody
	@PostMapping("/upload")
	@ApiOperation("上传文件")
	public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
		return mUploadService.uploadFile(file);
	}

	@RequestMapping("/addHouse")
	public String addHouse(Model model, HttpServletRequest request) {
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		if (userId !=null){
			User user = userService.getById(userId);
			model.addAttribute("user",user);
			return "house/addhouse";
		}
		else {
			User user = userService.getById(0);
			model.addAttribute("user",user);
			return "house/addhouse";
		}
	}

	@RequestMapping("/addHouseRecord")
	@ResponseBody
	public String addHouse(House houseVo) {
		if(houseVo.getPublisher()==null||"".equals(houseVo.getPublisher())) {
			houseVo.setPublisher("管理员");
		}
		Gson gson = new Gson();
		System.out.println(gson.toJson(houseVo));
		boolean n = houseService.saveOrUpdate(houseVo);
		if(n) {
			return "OK";
		}
		return "FAIL";
	}

	@RequestMapping("/updateHouse")
	@ResponseBody
	public String updateHouse(House house) {
		boolean b = houseService.saveOrUpdate(house);
		if(b) {
			return "OK";
		}
		return "FAIL";
	}

}
